﻿using System;
using System.Collections.Generic;
using System.IO;

namespace KMLHelper
{
    public class KMLDocument
    {
        private string name = null;
        /// <summary>
        /// 名称
        /// </summary>
        public string Name
        {
            set { this.name = value; }
        }

        private List<KMLPlacemark> placemarks;
        public List<KMLPlacemark> Placemarks
        {
            set { this.placemarks = value; }
            get { return this.placemarks; }
        }

        public bool Write(string kmlPath, ref string errMsg)
        {
            try
            {
                using (FileStream fs = File.Open(kmlPath, FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {                        
                        sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                        sw.WriteLine("<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">");
                        sw.WriteLine("<Document>");

                        sw.WriteLine("<name>" + name + "</name>");

                        foreach (KMLPlacemark placemark in this.placemarks)
                        {
                            placemark.Write(sw);
                        }

                        sw.WriteLine("</Document>");
                        sw.WriteLine("</kml>");
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return false;
            }
        }
    }
}
